package explore.hxx.binarytree.self;


import explore.hxx.binarytree.dependence.TreeNode;

/**
 * @author waxijiang
 */
public class IsSymmetric {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(2);
        root.left.left = new TreeNode(3);
        root.left.right = new TreeNode(4);
        root.right.left = new TreeNode(4);
        root.right.right = new TreeNode(3);
        System.out.println(isSymmetric(root));
    }

    public static boolean isSymmetric(TreeNode root) {
        if (root == null) {
            return true;
        }

        if (root.left != null && root.right != null) {
            return helper(root.left, root.right);
        } else if (root.left == null && root.right == null) {
            return true;
        } else if (root.left == null || root.right == null){
            return false;
        }
        return false;
    }

    public static boolean helper(TreeNode left, TreeNode right) {
        boolean flagLeft = false;
        boolean flagRight = false;

        // 根节点值不一样直接ｆａｌｓｅ
        if (left.val != right.val) {
            return false;
        }

        // 否则开始看其子节点,左左和右右
        if (left.left == null && right.right == null) {
            flagLeft = true;
        } else if (left.left == null || right.right == null) {
            flagLeft = false;
        } else if (left.left.val == right.right.val) {
            flagLeft = helper(left.left, right.right);
        }

        // 左右和右左
        if (left.right == null && right.left == null) {
            flagRight = true;
        } else if (left.right == null || right.left == null) {
            flagRight = false;
        } else if (left.right.val == right.left.val) {
            flagRight = helper(left.right, right.left);
        }

        if (flagLeft && flagRight) {
            return true;
        } else {
            return false;
        }

    }
}
